package com.sunday.common.doc.autoconfiguration;

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * OpenAPI 配置
 *
 * @author sunday
 * @since 2024/9/27
 */
@Configuration
public class OpenAPIConfiguration {

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info().title("springboot 中使用 Swagger UI 构建 RESTFul API")
                        .contact(new Contact())
                        .description("sunday 管理平台提供的 RESTFul API")
                        .version("v1.0.0")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org"))
                );
    }

    @Bean
    public OpenApiCustomizer globalHeaderOpenApiCustomizer() {
        return openApi -> {
            Parameter parameter = new Parameter()
                    .name("tokenInfo")
                    .description("令牌信息 例: {\"id\":1}")
                    .in(ParameterIn.HEADER.toString())
                    .required(false);

            List<Parameter> globalParameters = new ArrayList<>();
            globalParameters.add(parameter);

            if (openApi.getPaths() != null) {
                openApi.getPaths().values().forEach(pathItem ->
                        pathItem.readOperations().forEach(operation ->
                                operation.addParametersItem(parameter)));
            }
        };
    }

}
